<template>
  <div class="chat-container">
    <div class="message-list" ref="messageList">
      <div 
        v-for="message in messages" 
        :key="message.id" 
        :class="['message-item', message.isUser ? 'user-message' : 'assistant-message', 'animate-fade-in']"
        :style="{ animationDelay: `${message.id.includes('init') ? '0s' : '0.1s'}` }"
      >
        <div class="avatar">
          <img 
            :src="message.isUser ? userAvatar : assistantAvatar" 
            alt="avatar" 
            class="avatar-img"
          />
        </div>
        <div class="message-content">
          <template v-if="message.isLoading">
            <LoadingDots class="loading-indicator" />
          </template>
          <div v-else class="message-text" v-html="formatMessage(message.content)"></div>
        </div>
      </div>
    </div>
    
    <div class="input-area animate-fade-in" style="animation-delay: 0.3s">
      <!-- 新增功能按钮区域 -->
      <div class="function-buttons">
        <button 
          class="func-btn" 
          @click="useKnowledgeBase = !useKnowledgeBase" 
          :class="{ active: useKnowledgeBase }"
          title="点击开启：让模型从知识库检索信息"
          :disabled="isSending"
        >
          知识库
        </button>
        <button 
          class="func-btn" 
          @click="useRealTimeInfo = !useRealTimeInfo" 
          :class="{ active: useRealTimeInfo }"
          title="点击开启：让模型获取实时信息"
          :disabled="isSending"
        >
          实时信息
        </button>
      </div>
      
      <div class="input-wrapper" :class="{ 'input-focused': inputFocused }">
        <textarea 
          v-model="inputMessage" 
          placeholder="发消息，请输入..."
          @keyup.enter.exact.prevent="sendMessage"
          rows="1"
          class="message-input"
          @focus="inputFocused = true"
          @blur="inputFocused = false"
        ></textarea>
        <div 
          class="send-button" 
          @click="sendMessage" 
          :class="{ 'active': inputMessage.trim() }"
          :disabled="!inputMessage.trim()"
        >
          <svg t="1710400669747" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4231" width="24" height="24">
            <path d="M931.4 481.3L815.9 396l0.3-0.4-604.7-249c-3.8-1.6-7.9-1.9-11.9-1l-0.3-0.7L135 171.3c-12.3 2.7-20.3 14.8-17.6 27.1 0.9 4.3 3.1 8 6.2 10.9l-0.3 0.7 155.6 130.3L492.3 436l-213.4 95.7-140.9 118c-9.7 8.1-11 22.6-2.8 32.3 3.9 4.6 9.3 7.5 15.2 8.1l0.3 0.7 63.9 26.3c4 1.6 8.1 1.9 12.1 1l0.3 0.7 201.4-83 139.3 57.4c4 1.6 8.1 1.9 12.1 0.9l0.3 0.7 63.9-26.3c12.3-2.7 20.3-14.8 17.6-27.1-0.9-4.3-3.1-8-6.2-10.9l0.3-0.7-102.8-86 389.4-174.6c11.3-5.1 16.3-18.3 11.3-29.6-2.3-4.9-6-8.6-10.8-11z" p-id="4232"></path>
          </svg>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, nextTick, onMounted } from 'vue';
import LoadingDots from '@/components/common/LoadingDots.vue';
import { useLoginUserStore } from "@/store/user";
import { getApiUrl, API_PATHS } from '@/config/api';

// 定义消息类型接口
interface ChatMessage {
  id: string;
  isUser: boolean;
  content: string;
  isLoading?: boolean;
}

// 定义后端返回的历史记录项类型
interface HistoryItem {
  content: string;
  isAI: boolean;
  timestamp?: string;
}

// 定义后端响应格式类型
interface HistoryResponse {
  code: number;
  msg: string;
  data: HistoryItem[];
  total: number;
}

export default defineComponent({
  name: 'Chat',
  components: {
    LoadingDots,
  },
  setup() {
    // 聊天消息列表
    const messages = ref<ChatMessage[]>([]);
    const inputMessage = ref('');
    const messageList = ref<HTMLElement | null>(null);
    const inputFocused = ref(false);
    const isSending = ref(false); // 新增：发送状态控制
    
    // 新增功能状态
    const useKnowledgeBase = ref(false); // 知识库功能开关
    const useRealTimeInfo = ref(false); // 实时信息功能开关
    
    // 头像资源
    const userAvatar = require('@/assets/user-avatar.png');
    const assistantAvatar = require('@/assets/assistant-avatar.png');
    const loginStore = useLoginUserStore();

    // 消息格式化函数
    const formatMessage = (text: string): string => {
      if (!text) return '';
      let formattedText = text
        .replace(/\*\*(.*?)\*\*/g, '<span class="msg-bold">$1</span>')
        .replace(/(^|\n)\s*-\s(.*?)(?=\n|$)/g, (match, lineBreak, content) => {
          return `${lineBreak}<div class="msg-list-item"><span class="list-dash">-</span>${content}</div>`;
        })
        .replace(/\n/g, '<br>');
      return formattedText;
    };

    // 滚动到底部函数
    const scrollToBottom = () => {
      if (messageList.value) {
        messageList.value.scrollTop = messageList.value.scrollHeight;
      }
    };

    // 加载聊天历史记录函数
    const loadChatHistory = async () => {
      try {
        const token = loginStore.token;
        if (!token) {
          messages.value = [{
            id: 'init-' + Date.now(),
            isUser: false,
            content: '我是日落前的星星，来陪我聊天吧',
          }];
          await nextTick();
          scrollToBottom();
          return;
        }

        const response = await fetch(getApiUrl(API_PATHS.History), {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'token': token
          }
        });

        const resData: HistoryResponse = await response.json();
        if (!response.ok || resData.code !== 0) {
          throw new Error(resData.msg || `获取历史记录失败，状态码: ${response.status}`);
        }

        const formattedHistory: ChatMessage[] = resData.data.map((item, index) => ({
          id: `history-${index}-${item.timestamp || Date.now()}`,
          isUser: !item.isAI,
          content: item.content,
          isLoading: false
        }));

        if (formattedHistory.length === 0) {
          messages.value = [{
            id: 'init-' + Date.now(),
            isUser: false,
            content: '我是日落前的星星，来陪我聊天吧',
          }];
        } else {
          messages.value = formattedHistory;
        }

      } catch (error) {
        console.error('加载聊天历史失败:', error);
        messages.value = [{
          id: 'init-' + Date.now(),
          isUser: false,
          content: '我是日落前的星星，来陪我聊天吧',
        }];
      } finally {
        await nextTick();
        scrollToBottom();
      }
    };

    // 处理SSE流式响应
    const processStreamResponse = async (response: Response) => {
      const reader = response.body?.getReader();
      if (!reader) return;

      const currentMessageIndex = messages.value.length - 1;
      const decoder = new TextDecoder();
      let remainingData = '';

      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const decodedChunk = remainingData + decoder.decode(value, { stream: true });
          const lines = decodedChunk.split(/\r?\n/);
          remainingData = lines.pop() || '';

          for (const line of lines) {
            const trimmedLine = line.trim();
            if (trimmedLine === '') continue;

            if (trimmedLine.match(/^data:\s*\[\DONE\]$/)) {
              console.log('流式传输已结束');
              continue;
            }

            const jsonStr = trimmedLine.replace(/^data:\s*/, '').trim();
            if (!jsonStr) continue;

            try {
              const jsonData = JSON.parse(jsonStr);
              if (jsonData.code === 0 && typeof jsonData.data === 'string') {
                messages.value[currentMessageIndex].isLoading = false;
                messages.value[currentMessageIndex].content += jsonData.data;
                
                await nextTick();
                scrollToBottom();
              }
            } catch (e) {
              console.error('JSON解析失败', '原始数据:', jsonStr, '错误:', e);
            }
          }
        }

        if (remainingData.trim()) {
          const trimmedLine = remainingData.trim();
          if (!trimmedLine.match(/^data:\s*\[\DONE\]$/)) {
            const jsonStr = trimmedLine.replace(/^data:\s*/, '').trim();
            if (jsonStr) {
              try {
                const jsonData = JSON.parse(jsonStr);
                if (jsonData.code === 0 && typeof jsonData.data === 'string') {
                  messages.value[currentMessageIndex].isLoading = false;
                  messages.value[currentMessageIndex].content += jsonData.data;
                  await nextTick();
                  scrollToBottom();
                }
              } catch (e) {
                console.error('最后一段数据解析失败', jsonStr, e);
              }
            }
          }
        }

      } catch (error) {
        console.error('流式读取异常:', error);
        messages.value[currentMessageIndex] = {
          id: messages.value[currentMessageIndex].id,
          isUser: false,
          content: '[读取数据时发生错误，请稍后重试]',
          isLoading: false
        };
      } finally {
        messages.value[currentMessageIndex].isLoading = false;
        isSending.value = false; // 重置发送状态
        await nextTick();
        scrollToBottom();
      }
    };

    // 发送消息函数（添加了功能后缀处理）
    const sendMessage = async () => {
      const messageText = inputMessage.value.trim();
      if (!messageText) return;

      // 根据功能开关添加相应后缀
      let finalText = messageText;
      if (useKnowledgeBase.value) {
        finalText += '（请务必前往知识库搜索）';
      }
      if (useRealTimeInfo.value) {
        finalText += '（需要实时信息）';
      }

      isSending.value = true; // 设置发送状态

      // 添加用户消息到列表（显示原始输入）
      const userMsgId = 'user-' + Date.now() + Math.random().toString(36).slice(2, 8);
      messages.value.push({
        id: userMsgId,
        isUser: true,
        content: messageText
      });

      // 添加AI加载消息
      const aiMsgId = 'ai-' + Date.now() + Math.random().toString(36).slice(2, 8);
      messages.value.push({
        id: aiMsgId,
        isUser: false,
        content: '',
        isLoading: true
      });

      // 清空输入框并滚动到底部
      inputMessage.value = '';
      await nextTick();
      scrollToBottom();

      try {
        // 发起SSE请求（发送带后缀的文本）
        const response = await fetch(getApiUrl(API_PATHS.CHAT), {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            token: loginStore.token || ''
          },
          body: JSON.stringify({
            message: finalText // 发送处理后的文本
          })
        });

        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(`服务端错误 ${response.status}: ${errorText}`);
        }

        // 处理流式响应
        await processStreamResponse(response);

      } catch (error) {
        console.error('发送消息失败:', error);
        messages.value.pop(); // 移除加载中的AI消息
        messages.value.push({
          id: 'error-' + Date.now(),
          isUser: false,
          content: '抱歉，发送消息失败，请稍后重试。',
          isLoading: false
        });
        isSending.value = false; // 重置发送状态
      } finally {
        await nextTick();
        scrollToBottom();
      }
    };

    // 组件初始化时加载历史记录
    onMounted(() => {
      loadChatHistory();
    });

    return {
      messages,
      inputMessage,
      messageList,
      sendMessage,
      userAvatar,
      assistantAvatar,
      inputFocused,
      formatMessage,
      useKnowledgeBase, // 暴露状态到模板
      useRealTimeInfo,  // 暴露状态到模板
      isSending         // 暴露状态到模板
    };
  }
});
</script>

<style scoped>
/* 基础布局 */
.chat-container { display: flex; flex-direction: column; height: 100vh; background: #f8fafc; }
.message-list { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 16px; }
.message-item { display: flex; gap: 12px; max-width: 80%; animation-fill-mode: both; }
.message-item.user-message { margin-left: auto; flex-direction: row-reverse; }
.message-item.user-message .message-content { background: #e6f7ff; color: #001529; border-top-right-radius: 4px; }
.message-item.assistant-message { margin-right: auto; }
.message-item.assistant-message .message-content { background: #fff; color: #001529; border-top-left-radius: 4px; }

/* 头像样式 */
.avatar { width: 40px; height: 40px; border-radius: 50%; overflow: hidden; flex-shrink: 0; box-shadow: 0 2px 6px rgba(0,0,0,0.1); }
.avatar-img { width: 100%; height: 100%; object-fit: cover; transition: transform 0.3s ease; }
.avatar-img:hover { transform: scale(1.05); }

/* 消息内容 */
.message-content {
  padding: 12px 16px 12px 20px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.6;
  word-break: break-word;
  white-space: pre-wrap;
  min-height: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}
.message-text { animation: fadeIn 0.5s ease; }
.loading-indicator { display: flex; align-items: center; justify-content: center; height: 40px; }

/* 加粗和列表样式 */
.message-text .msg-bold {
  font-weight: 700;
  font-size: 1.15em;
  margin: 0 2px;
  transition: color 0.2s ease;
}
.assistant-message .message-text .msg-bold {
  color: #0047ab;
}
.user-message .message-text .msg-bold {
  color: #003366;
}
.message-text .msg-list-item {
  position: relative;
  padding-left: 14px;
  margin: 6px 0;
  line-height: 1.7;
}
.message-text .list-dash {
  position: absolute;
  left: 0;
  font-size: 1.3em;
  font-weight: 600;
}
.assistant-message .message-text .list-dash {
  color: #409eff;
}
.user-message .message-text .list-dash {
  color: #1890ff;
}

/* 输入区域 */
.input-area { padding: 16px 20px; background: #fff; border-top: 1px solid #e2e8f0; display: flex; align-items: center; gap: 10px; }

/* 新增功能按钮样式 */
.function-buttons { display: flex; gap: 8px; margin-right: 4px; }
.func-btn { 
  padding: 6px 12px; 
  font-size: 14px; 
  border-radius: 18px; 
  border: 1px solid #e2e8f0; 
  background: transparent; 
  cursor: pointer; 
  transition: all 0.2s ease;
  white-space: nowrap;
  color: #64748b;
}
.func-btn:hover:not(.active) { 
  background: #f1f5f9; 
  border-color: #cbd5e1;
  color: #334155;
}
.func-btn.active { 
  background: #409eff; 
  color: white; 
  border-color: #409eff;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
}
.func-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.input-wrapper { position: relative; flex: 1; max-width: 1080px; min-height: 60px; margin: 0 auto; background: #fff; border-radius: 24px; border: 2px solid #e2e8f0; padding: 14px 60px 14px 20px; transition: all 0.2s; }
.input-focused { border-color: #409eff; box-shadow: 0 0 0 3px rgba(64,158,255,0.1); }
.message-input { width: 100%; border: none; background: transparent; resize: none; outline: none; font-size: 14px; line-height: 1.5; max-height: 180px; overflow-y: auto; }

/* 发送按钮 */
.send-button { position: absolute; right: 12px; bottom: 12px; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 50%; transition: all 0.3s; }
.send-button:disabled { opacity: 0.6; cursor: not-allowed; }
.send-button svg { fill: #94a3b8; transition: all 0.3s; }
.send-button.active svg { fill: #409eff; }
.send-button:hover:not(:disabled) { background: rgba(64,158,255,0.1); transform: scale(1.05); }
.send-button.active:hover:not(:disabled) { background: rgba(64,158,255,0.2); }

/* 滚动条样式 */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 3px; }
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #94a3b8; }

/* 动画类 */
.animate-fade-in { animation: fadeIn 0.4s ease forwards; opacity: 0; }

/* 动画关键帧 */
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

/* 响应式适配 - 平板 */
@media (max-width: 968px) {
  .message-list { padding: 16px; gap: 12px; }
  .message-item { max-width: 85%; }
  .message-content { padding: 12px 14px 12px 18px; }
  .message-text .msg-bold { font-size: 1.1em; }
  .message-text .list-dash { font-size: 1.2em; }
  .message-text .msg-list-item { padding-left: 12px; }
  .input-area { padding: 12px 16px; gap: 6px; }
  .func-btn { padding: 5px 10px; font-size: 13px; }
  .input-wrapper { padding: 12px 56px 12px 16px; }
}

/* 响应式适配 - 手机 */
@media (max-width: 576px) {
  .message-list { padding: 12px; gap: 10px; }
  .message-item { max-width: 90%; }
  .avatar { width: 36px; height: 36px; }
  .message-content { 
    padding: 10px 12px 10px 16px;
    font-size: 13px; 
    border-radius: 8px; 
  }
  .message-text .msg-bold { font-size: 1.05em; }
  .message-text .list-dash { font-size: 1.15em; }
  .message-text .msg-list-item { padding-left: 10px; margin: 5px 0; }
  .input-area { padding: 10px 12px; gap: 4px; }
  .func-btn { padding: 3px 8px; font-size: 12px; }
  .input-wrapper { min-height: 50px; border-radius: 20px; padding: 10px 50px 10px 14px; }
  .message-input { font-size: 13px; }
  .send-button { width: 32px; height: 32px; }
  .send-button svg { width: 20px; height: 20px; }
}
</style>